package DB;

import java.sql.*;

public class userLib {
    public static User loginOK(String userName, String passWord) throws SQLException {
        String sql = "select * from\n" +
                "             UserLib\n" +
                "where userName=? and password=?";
        try (Connection conn = JDBC.getConnection();
             PreparedStatement preparedStatement = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            preparedStatement.setString(1, userName);
            preparedStatement.setString(2, passWord);
            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                User user=new User();
                user.setUserName(resultSet.getString("userName"));
                user.setPassWord(resultSet.getString("passWord"));
                user.setRole(resultSet.getString("role"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;

    }
    public static boolean addUser(String userName,String passWard,String name,int age,String gender,String id,String phoneNumber,String email,String role) throws SQLException {
        String sql="insert into userlib\n" +
                "(userName, passWord, name, age, gender, id, phoneNumber, email,role) VALUES \n" +
                "                                                                    (?,?,?,?,?,?,?,?,?)";
        String selectSQL="select * from userlib\n" +
                "where userName=?";
        Connection connection=JDBC.getConnection();
        PreparedStatement preparedStatement=null;
        preparedStatement=connection.prepareStatement(selectSQL);
        preparedStatement.setString(1,userName);
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()){
            preparedStatement.close();
            JDBC.close(connection);
            return false;
        }
        preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setString(1,userName);
        preparedStatement.setString(2,passWard);
        preparedStatement.setString(3,name);
        preparedStatement.setInt(4,age);
        preparedStatement.setString(5,gender);
        preparedStatement.setString(6,id);
        preparedStatement.setString(7,phoneNumber);
        preparedStatement.setString(8,email);
        preparedStatement.setString(9,role);
        int a = preparedStatement.executeUpdate();
        System.out.println(a);

        preparedStatement.close();
        JDBC.close(connection);
        return true;
    }
}
